package com.example.educationalsystem.controller;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.educationalsystem.common.util.DateFormates;
import com.example.educationalsystem.common.util.ExcelListener;
import com.example.educationalsystem.common.util.ResponseJson;
import com.example.educationalsystem.common.util.UploadFileService;
import com.example.educationalsystem.entity.Score;
import com.example.educationalsystem.entity.Student;
import com.example.educationalsystem.entity.Teacher;
import com.example.educationalsystem.entity.User;
import com.example.educationalsystem.entity.Vo.ScoreVo;
import com.example.educationalsystem.service.IStudentService;
import com.example.educationalsystem.service.ITeacherService;
import com.example.educationalsystem.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author zpc
 * @since 2022-12-02
 */
@Api(value = "/user", tags = "用户管理")
@RestController
@RequestMapping("/user")
public class UserController {


    @Autowired
    private IUserService iUserService;

    @Autowired
    private ITeacherService iTeacherService;

    @Autowired
    private IStudentService iStudentService;

    @Autowired
    private UploadFileService uploadFileService;

    @ApiOperation(value = "导入用户信息", notes = "导入用户信息")
    @ResponseBody
    @PostMapping("Import")
    public ResponseJson myImport(MultipartFile file) {
        ResponseJson responseJson = new ResponseJson();
        try {
            //获取文件名
            String filename = file.getOriginalFilename();
            //获取文件流
            InputStream inputStream = file.getInputStream();
            //实例化实现了AnalysisEventListener接口的类
            ExcelListener listener = new ExcelListener();

            EasyExcelFactory.read(inputStream, User.class, listener).headRowNumber(1).build().readAll();
            //获取数据
            List<Object> list = listener.getDatas();
            System.out.println(list.size());
            if (list.size() >= 1) {
                for (int i = 0; i < list.size(); i++) {
                    User user = (User) list.get(i);

                    //使用mybatis-plus添加到数据库
                    Boolean res = iUserService.save(user);
                    if (res) {
                        responseJson.setStatus(200);
                        responseJson.setMsg("导入成功！");
                    } else {
                        responseJson.setStatus(400);
                        responseJson.setMsg("导入失败！");
                    }
                    System.out.println(res);
                }
            }

        } catch (Exception e) {
            responseJson.setStatus(400);
            responseJson.setMsg(e.toString());
            e.printStackTrace();
        }

        return responseJson;
    }

    @ApiOperation(value = "导出所有用户信息", notes = "导出所有用户信息")
    @ResponseBody
    @GetMapping("Download")
    public void myDownload(HttpServletResponse response, @RequestParam String tableName) throws IOException {

        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename=" + new String(tableName.getBytes(StandardCharsets.UTF_8), "ISO8859-1") + ".xls");
            EasyExcel.write(response.getOutputStream(), User.class).sheet(tableName).doWrite(iUserService.getBaseMapper().selectList(Wrappers.lambdaQuery()));


        } catch (Exception e) {
            response.reset();
        }


    }

    /**
     * @return com.example.educationalsystem.common.util.ResponseJson
     * @throws
     * @Param : []
     * @Description : 查询所有用户信息
     * @Author : zpc20
     * @Date : 2022/12/2 9:15
     */
    @ApiOperation(value = "查询用户信息", notes = "获取用户信息")
    @GetMapping("/getAllUser")
    public ResponseJson getAllUser() {
        ResponseJson responseJson = new ResponseJson();
        List<User> userList = iUserService.getBaseMapper().selectList(Wrappers.lambdaQuery());
        if (userList.isEmpty()) {
            responseJson.setStatus(404);
            responseJson.setMsg("暂无用户！");
        } else {
            responseJson.setStatus(200);
            responseJson.setMsg("查询成功！");
            responseJson.setData(userList);
        }

        return responseJson;
    }


    @ApiOperation(value = "分页查询用户信息", notes = "分页查询用户信息，需要提供页数和一页大小（即一页几条数据）")
    @GetMapping(value = "/userpage")
    @ResponseBody
    public ResponseJson userpage(@RequestParam long current, @RequestParam long size) {
        ResponseJson responseJson = new ResponseJson();
        Page<User> userPage = new Page<>(current, size);
        Page<User> userPages = iUserService.getBaseMapper().selectPage(userPage, null);
        responseJson.setMsg("分页查询成功");
        responseJson.setData(userPages);
        responseJson.setStatus(200);
        return responseJson;
    }

    @ApiOperation(value = "用户注册", notes = "用户注册，用户ID不用填写")
    @PostMapping(value = "/insertUser")
    @ResponseBody
    public ResponseJson insertUser(
            @RequestParam("username") String username,
            @RequestParam(value = "file") MultipartFile file,
            @RequestParam("password") String password,
            @RequestParam("email") String email,
            @RequestParam("phone") String phone,
            @RequestParam("identity") String identity
    ) throws IOException {
        User requestUser = new User();
        requestUser.setUserName(username);
        requestUser.setUserPassword(password);
        requestUser.setUserEmail(email);
        String strID = DateFormates.NowDateFormate();

        if (identity.matches("管理员")) {
            requestUser.setUserPermissions(3);
        } else if (identity.matches("教师")) {
            requestUser.setUserPermissions(2);
        } else if (identity.matches("学生")) {
            requestUser.setUserPermissions(1);
        }
        requestUser.setUserPhone(phone);
        requestUser.setUserIdentity(identity);
        String url = uploadFileService.uploads(file, "AvatarUrl");
        System.out.println(url);
        requestUser.setUserAvatarUrl(url);
        ResponseJson responseJson = new ResponseJson();
        /**
         * 检测用户是否重名
         */
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        User repeat_name = iUserService.getBaseMapper().selectOne(queryWrapper.eq("user_name", username));
        //获取存储用户的及基本信息
        if (repeat_name == null) {
            //密码加密
            String mm = new BCryptPasswordEncoder().encode(requestUser.getUserPassword());
            System.out.println("加密后的密码：");
            System.out.println(mm);
            requestUser.setUserPassword(mm);
            Boolean result = iUserService.save(requestUser);
            if (result) {
                if (requestUser.getUserPermissions() == 2) {
                    Teacher teacher = new Teacher();
                    teacher.setTeacherName(username);
                    teacher.setTeacherPhone(phone);
                    teacher.setTeacherId(strID);
                    iTeacherService.save(teacher);
                } else if (requestUser.getUserPermissions() == 1) {
                    Student student = new Student();
                    student.setStudentName(username);
                    student.setStudentId(strID);
                    iStudentService.save(student);
                }
                responseJson.setStatus(200);
                responseJson.setMsg("注册成功");
                responseJson.setData(requestUser);
            } else {
                responseJson.setStatus(400);
                responseJson.setMsg("注册失败");
//               ajaxJson.setObj(requestUser);
            }

        } else {
            responseJson.setStatus(400);
            responseJson.setMsg("注册失败,用户名重复");
        }
        return responseJson;
    }

    @ApiOperation(value = "批量删除用户信息", notes = "根据用户编号，删除多条用户信息")
    @DeleteMapping("/deleteUsers")
    @ResponseBody
    public ResponseJson deleteUsers(@ApiParam(name = "Ids", value = "用户IDs", required = true) @RequestParam String
                                            Ids) {
        ResponseJson responseJson = new ResponseJson();
        String[] idArr = Ids.split(",");
        List<String> idList = Arrays.asList(idArr);
        boolean result = iUserService.removeByIds(idList);
        System.out.println(result);
        if (result) {
//            responseJson.setData(courseOne);
            responseJson.setMsg("批量删除成功！");
            responseJson.setStatus(200);
        } else {
            responseJson.setMsg("批量删除失败");
            responseJson.setStatus(400);
        }
        return responseJson;

    }

    @ApiOperation(value = "注销用户", notes = "注销用户，需要填写用户名密码")
    @DeleteMapping("/delete")
    @ResponseBody
    public ResponseJson delete(@ApiParam(name = "UserName", value = "用户名", required = true) @RequestParam String UserName, @ApiParam(name = "Password", value = "密码", required = true) @RequestParam String
            Password) {
        ResponseJson responseJson = new ResponseJson();
        Map<String, Object> objectMap = new HashMap<>();
        objectMap.put("user_name", UserName);
        objectMap.put("user_password", Password);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        User UserOne = iUserService.getBaseMapper().selectOne(queryWrapper.eq("user_name", UserName).eq("user_password", Password));
        if (UserOne != null) {
            iUserService.getBaseMapper().deleteByMap(objectMap);
            responseJson.setMsg("删除成功！");
            responseJson.setStatus(200);
            responseJson.setData(UserOne);
        } else {
            responseJson.setMsg("该用户未注册");
            responseJson.setStatus(400);
        }
        return responseJson;
    }

    @ApiOperation(value = "用户信息更新", notes = "更新用户信息，必须填写用户ID")
    @PutMapping("/update")
    @ResponseBody
    public ResponseJson update(@RequestBody User requestUser) {
        ResponseJson responseJson = new ResponseJson();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        User userOne = iUserService.getBaseMapper().selectOne(queryWrapper.eq("user_name", requestUser.getUserName()));
        if (userOne != null) {
            String mm = new BCryptPasswordEncoder().encode(requestUser.getUserPassword());
            System.out.println("加密后的密码：");
            System.out.println(mm);
            requestUser.setUserPassword(mm);
            QueryWrapper<User> queryWrapper1 = new QueryWrapper<>();
            int result = iUserService.getBaseMapper().update(requestUser, queryWrapper1.eq("user_name", requestUser.getUserName()));
            if (result == 1) {
                responseJson.setData(requestUser);
                responseJson.setMsg("更新成功！");
                responseJson.setStatus(200);
            } else {
                responseJson.setMsg("更新失败！");
                responseJson.setStatus(400);
            }
        } else {
            responseJson.setStatus(404);
            responseJson.setMsg("not found");
        }
        return responseJson;
    }


}

